<?php

class AnnouncementController extends AppController
{
    # Controller Name to be used
    var $name = 'Announcement';

    # Models to be used
    var $uses = array(
        'StudentUser','StaffUser','Announcement','StudentNotification'
    );

    # set the layout to use
    var $layout = 'staff_layout';

    function __validateLoginStatus()
    {
        if ($this->params['action'] != 'login' && $this->params['action'] != 'logout') {
            if ($this->Session->check('loginData') == false) {
                $this->redirect(array('action' => 'login?ref=' . $this->params['action']));
            } else {
                $auth_user = $this->Session->read('loginData');
                //check if the user has not done multiple login
                $db_login_session = $this->getLoginSession($auth_user['id']);
                $login_session = $auth_user['login_session'];
                if ($db_login_session != $login_session) {
                    $this->Session->setFlash('Your session has expired!');
                    $this->redirect(array('action' => 'logout'));
                }
                //authorize the user, if the user is not authorized to view this page then redirect them to their session
                //$auth_user = $this->Session->read('loginData');
                if ($auth_user['user_type'] != 'staff_user') {
                    if ($auth_user['user_type'] == 'student_user') {
                        $this->redirect(array('controller' => 'Student', 'action' => 'index'));
                    } elseif ($auth_user['user_type'] == 'bank_user') {
                        $this->redirect(array('controller' => 'Bank', 'action' => 'index'));
                    } else {
                        $this->redirect(array('action' => 'logout'));
                    }
                } /*else { // For non Admin Staff only
                    $user_level = $auth_user['user_level'];
                    if ($user_level == 'Admin') {
                        $this->redirect(array('controller' => 'StaffAdmin', 'action' => 'index'));
                    }
                }*/
            }
        }
    }

    private function getLoginSession($user_id)
    {
        $data = $this->StaffUser->find('first', array(
            'conditions' => array('id' => $user_id),
            'recursive' => -1
        ));
        return $data['StaffUser']['login_session'];
    }

    function  beforeFilter()
    {
        parent::beforeFilter();
        $this->__validateLoginStatus();
    }

    # Controller actions
    /**
     * @name index
     * @param void
     * @return Array of data.
     * @access public
     */
    function index()
    {
        $this->redirect(array('controller' => 'Announcement', 'action' => 'announcement'));
    }


    function announcement($type = 'get')
    {
        if ($this->request->is('ajax')) {
            $this->autoRender = false;
            $this->autoLayout = false;
            $auth_user = $this->Session->read('loginData');
            switch ($type) {
                case 'get' :
                    $_POST = $this->Announcement->sanitize($_POST);
                    /**  Get posted data */
                    $page = isset($_POST['page']) ? $_POST['page'] : 1;
                    /** The current page */
                    $sortname = isset($_POST['sortname']) ? $_POST['sortname'] : 'id';
                    /** Sort column */
                    $sortorder = isset($_POST['sortorder']) ? $_POST['sortorder'] : 'desc';
                    /** Sort order */
                    $qtype = isset($_POST['qtype']) ? $_POST['qtype'] : '';
                    /** Search column */
                    $search_query = isset($_POST['query']) ? $_POST['query'] : '';
                    /** Search string */
                    $rp = isset($_POST['rp']) ? $_POST['rp'] : 10;
                    $limit = $rp;
                    $start = ($page - 1) * $rp;

                    //get users id for this company only

                    /*$condition_array = array(
                        'StaffUser.deleted' => 'n'
                    );*/

                    if (!empty($search_query)) {
                        if ($qtype == 'username') {
                            /*$condition_array = array(
                                'User.username' => $search_query,
                                'User.deleted' => 'n'
                            );*/
                        } else {
                            /* $condition_array = array(
                                 "User.$qtype LIKE" => $search_query . '%',
                                 'User.deleted' => 'n'
                             );*/
                        }
                    }

                    //$data_table = $this->Announcement->find('all', array('conditions' => $condition_array, 'order' => "StaffUser.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
                    $data_table = $this->Announcement->find('all', array('order' => "Announcement.$sortname $sortorder", 'limit' => $start . ',' . $limit, 'recursive' => -1));
                    $data_table_count = $this->Announcement->find('count', array('recursive' => -1));

                    $total_records = $data_table_count;

                    if ($data_table) {
                        $return_arr = array();
                        foreach ($data_table as $obj) {
                            $return_arr[] = array(
                                'id' => $obj['Announcement']['id'],
                                'cell' => array(
                                    $obj['Announcement']['id'],
                                    $obj['Announcement']['created'],
                                    $obj['Announcement']['title'],
                                    $obj['Announcement']['message']
                                )
                            );
                        }
                        return json_encode(array('success' => true, 'total' => $total_records, 'page' => $page, 'rows' => $return_arr));
                    } else {
                        return json_encode(array('success' => false, 'total' => $total_records, 'page' => $page, 'rows' => array()));
                    }
                    break;

                case 'save':
                    $data = array(
                        'id' => $_POST['id'],
                        'title' => $_POST['title'],
                        'message' => $_POST['message'],
                        'created_by' => $auth_user['id'],
                    );
                    if ($this->Announcement->save($data)) {
                        //Blast Student
                        $sql = "INSERT INTO student_notifications (
                                  student_user_id,
                                  notify_title,
                                  notify_msg,
                                        created
                                )
                                SELECT id,
                                       '".$_POST['title']."',
                                       '".$_POST['message']."',
                                       CURDATE()
                                FROM student_users;";
                        $this->StudentNotification->query($sql);
                        return json_encode(array('code' => 0, 'msg' => 'Message has been sent.'));
                    } else {
                        echo json_encode(array('code' => 1, 'msg' => 'Message could not be sent.'));
                    }

                    break;
            }
        }

        $this->set(compact(''));
    }

}